package com.hcy.asyncfiledownload.datamodule.mq;

import com.hcy.asyncfiledownload.common.entry.ExportRecord;
import com.hcy.asyncfiledownload.common.event.MockMqExportEvent;
import com.hcy.asyncfiledownload.datamodule.service.provider.CenterHandler;
import com.hcy.asyncfiledownload.datamodule.service.provider.ExportHandler;
import com.hcy.asyncfiledownload.datamodule.service.provider.RunnerProvider;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @Author huchenying
 * @Date 2022/9/6 15:18
 * @Description 通过spring事件监听模拟mq consumer
 */
@Component
@Log4j2
public class MockMqConsumerExport implements ApplicationListener<MockMqExportEvent> {

    private final LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    private final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 10, TimeUnit.MINUTES, queue, (ThreadFactory) r -> {
        Thread thread = new Thread(r);
        thread.setName("mq export");
        return thread;
    }, new ThreadPoolExecutor.CallerRunsPolicy());

    @Override
    public void onApplicationEvent(MockMqExportEvent event) {
        log.info("receive message content -> {}", ToStringBuilder.reflectionToString(event.getExportRecord()));
        ExportHandler provider = CenterHandler.getProvider(event.getExportRecord().getProviderType());
        ExportRecord exportRecord = event.getExportRecord();
        if(exportRecord == null){
            throw new RuntimeException("exportRecord is null");
        }
        executor.execute(new RunnerProvider(provider,exportRecord));
    }
}
